{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1665a5cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import re\n",
    "import time\n",
    "import json\n",
    "import sqlite3\n",
    "from dotenv import load_dotenv\n",
    "import gradio as gr\n",
    "from openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cb6632c",
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv()\n",
    "client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"))\n",
    "DB_PATH = \"nova_support.db\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cd3ac8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_db():\n",
    "    conn = sqlite3.connect(DB_PATH)\n",
    "    cur = conn.cursor()\n",
    "    cur.execute(\"\"\"\n",
    "        CREATE TABLE IF NOT EXISTS tickets (\n",
    "            ticket_id TEXT PRIMARY KEY,\n",
    "            name TEXT,\n",
    "            company TEXT,\n",
    "            email TEXT,\n",
    "            issue TEXT,\n",
    "            priority TEXT,\n",
    "            status TEXT,\n",
    "            created_at TEXT\n",
    "        )\n",
    "    \"\"\")\n",
    "    conn.commit()\n",
    "    conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70e0556c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def new_ticket_id():\n",
    "    conn = sqlite3.connect(DB_PATH)\n",
    "    cur = conn.cursor()\n",
    "    cur.execute(\"SELECT COUNT(*) FROM tickets\")\n",
    "    count = cur.fetchone()[0]\n",
    "    conn.close()\n",
    "    return f\"RT-{1001 + count}\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38525d5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_ticket(name, company, email, issue, priority=\"P3\"):\n",
    "    tid = new_ticket_id()\n",
    "    ts = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n",
    "    conn = sqlite3.connect(DB_PATH)\n",
    "    cur = conn.cursor()\n",
    "    cur.execute(\"\"\"\n",
    "        INSERT INTO tickets (ticket_id, name, company, email, issue, priority, status, created_at)\n",
    "        VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n",
    "    \"\"\", (tid, name, company, email, issue, priority.upper(), \"OPEN\", ts))\n",
    "    conn.commit()\n",
    "    conn.close()\n",
    "    return tid, ts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58e803c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_ticket(ticket_id):\n",
    "    conn = sqlite3.connect(DB_PATH)\n",
    "    cur = conn.cursor()\n",
    "    cur.execute(\"SELECT * FROM tickets WHERE ticket_id=?\", (ticket_id,))\n",
    "    row = cur.fetchone()\n",
    "    conn.close()\n",
    "    if not row:\n",
    "        return None\n",
    "    keys = [\"ticket_id\", \"name\", \"company\", \"email\", \"issue\", \"priority\", \"status\", \"created_at\"]\n",
    "    return dict(zip(keys, row))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b97601ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "def synthesize_speech(text):\n",
    "    if not text.strip():\n",
    "        return None\n",
    "    output_path = Path(tempfile.gettempdir()) / \"nova_reply.mp3\"\n",
    "    with client.audio.speech.with_streaming_response.create(\n",
    "        model=\"gpt-4o-mini-tts\",\n",
    "        voice=\"alloy\",\n",
    "        input=text\n",
    "    ) as response:\n",
    "        response.stream_to_file(output_path)\n",
    "    return str(output_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4e20aad",
   "metadata": {},
   "outputs": [],
   "source": [
    "SYSTEM_PROMPT = \"\"\"\n",
    "You are Nova, the AI Support and Sales Assistant for Reallytics.ai.\n",
    "You help customers with:\n",
    "- Reporting issues (create tickets)\n",
    "- Checking existing tickets\n",
    "- Providing product/service information\n",
    "- Explaining pricing ranges\n",
    "- Reassuring integration compatibility with client systems\n",
    "Respond in a professional, business tone.\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d1c094d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def detect_intent(message):\n",
    "    text = message.lower()\n",
    "    if any(k in text for k in [\"create ticket\", \"open ticket\", \"new ticket\", \"issue\", \"problem\"]):\n",
    "        return \"create_ticket\"\n",
    "    if re.search(r\"rt-\\d+\", text):\n",
    "        return \"check_ticket\"\n",
    "    if \"price\" in text or \"cost\" in text:\n",
    "        return \"pricing\"\n",
    "    if \"integration\" in text:\n",
    "        return \"integration\"\n",
    "    return \"general\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed9114d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history, model, name, company, email):\n",
    "    history_msgs = [{\"role\": h[\"role\"], \"content\": h[\"content\"]} for h in history]\n",
    "    intent = detect_intent(message)\n",
    "\n",
    "    if intent == \"create_ticket\":\n",
    "        priority = \"P2\" if \"urgent\" in message.lower() or \"high\" in message.lower() else \"P3\"\n",
    "        tid, ts = create_ticket(name, company, email, message, priority)\n",
    "        text = f\"A new support ticket has been created.\\nTicket ID: {tid}\\nCreated at: {ts}\\nStatus: OPEN\"\n",
    "        yield text, synthesize_speech(text)\n",
    "        return\n",
    "\n",
    "    if intent == \"check_ticket\":\n",
    "        match = re.search(r\"(rt-\\d+)\", message.lower())\n",
    "        if match:\n",
    "            ticket_id = match.group(1).upper()\n",
    "            data = get_ticket(ticket_id)\n",
    "            if data:\n",
    "                text = (\n",
    "                    f\"Ticket {ticket_id} Details:\\n\"\n",
    "                    f\"Issue: {data['issue']}\\n\"\n",
    "                    f\"Status: {data['status']}\\n\"\n",
    "                    f\"Priority: {data['priority']}\\n\"\n",
    "                    f\"Created at: {data['created_at']}\"\n",
    "                )\n",
    "            else:\n",
    "                text = f\"No ticket found with ID {ticket_id}.\"\n",
    "        else:\n",
    "            text = \"Please provide a valid ticket ID.\"\n",
    "        yield text, synthesize_speech(text)\n",
    "        return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "280c7d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history, model, name, company, email):\n",
    "    if not message.strip():\n",
    "        yield \"Please type a message to start.\", None\n",
    "        return\n",
    "\n",
    "    history_msgs = [{\"role\": h[\"role\"], \"content\": h[\"content\"]} for h in history]\n",
    "    intent = detect_intent(message)\n",
    "    reply, audio_path = \"\", None\n",
    "\n",
    "    if intent == \"create_ticket\":\n",
    "        priority = \"P2\" if \"urgent\" in message.lower() or \"high\" in message.lower() else \"P3\"\n",
    "        tid, ts = create_ticket(name, company, email, message, priority)\n",
    "        reply = f\"A new support ticket has been created.\\nTicket ID: {tid}\\nCreated at: {ts}\\nStatus: OPEN\"\n",
    "        audio_path = synthesize_speech(reply)\n",
    "        yield reply, audio_path\n",
    "        return\n",
    "\n",
    "    if intent == \"check_ticket\":\n",
    "        match = re.search(r\"(rt-\\d+)\", message.lower())\n",
    "        if match:\n",
    "            ticket_id = match.group(1).upper()\n",
    "            data = get_ticket(ticket_id)\n",
    "            if data:\n",
    "                reply = (\n",
    "                    f\"Ticket {ticket_id} Details:\\n\"\n",
    "                    f\"Issue: {data['issue']}\\n\"\n",
    "                    f\"Status: {data['status']}\\n\"\n",
    "                    f\"Priority: {data['priority']}\\n\"\n",
    "                    f\"Created at: {data['created_at']}\"\n",
    "                )\n",
    "            else:\n",
    "                reply = f\"No ticket found with ID {ticket_id}.\"\n",
    "        else:\n",
    "            reply = \"Please provide a valid ticket ID.\"\n",
    "        audio_path = synthesize_speech(reply)\n",
    "        yield reply, audio_path\n",
    "        return\n",
    "\n",
    "    messages = [{\"role\": \"system\", \"content\": SYSTEM_PROMPT}] + history_msgs + [{\"role\": \"user\", \"content\": message}]\n",
    "    stream = client.chat.completions.create(model=model, messages=messages, stream=True)\n",
    "\n",
    "    full_reply = \"\"\n",
    "    for chunk in stream:\n",
    "        delta = chunk.choices[0].delta.content or \"\"\n",
    "        full_reply += delta\n",
    "        yield full_reply, None  \n",
    "    audio_path = synthesize_speech(full_reply)\n",
    "    yield full_reply, audio_path "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0cb1977d",
   "metadata": {},
   "outputs": [],
   "source": [
    "init_db()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a0557ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "with gr.Blocks(title=\"Nova | Business AI Assistant\", theme=gr.themes.Soft()) as demo:\n",
    "    gr.Markdown(\"## Nova | Reallytics.ai Customer Support & Sales Assistant\")\n",
    "    gr.Markdown(\n",
    "        \"Nova helps clients create or track support tickets, understand services, and explore automation options. \"\n",
    "        \"Type your questions and Nova will respond in both text and voice.\"\n",
    "    )\n",
    "\n",
    "    with gr.Row():\n",
    "        name = gr.Textbox(label=\"Your Name\", placeholder=\"Liam\")\n",
    "        company = gr.Textbox(label=\"Company (optional)\", placeholder=\"ABC Corp\")\n",
    "    email = gr.Textbox(label=\"Email\", placeholder=\"you@example.com\")\n",
    "\n",
    "    model = gr.Dropdown([\"gpt-4o-mini\", \"gpt-4\", \"gpt-3.5-turbo\"], value=\"gpt-4o-mini\", label=\"Model\")\n",
    "\n",
    "    audio_output = gr.Audio(label=\"Nova's Voice Reply\", autoplay=True, interactive=False)\n",
    "\n",
    "    gr.ChatInterface(\n",
    "        fn=chat,\n",
    "        type=\"messages\",\n",
    "        additional_inputs=[model, name, company, email],\n",
    "        additional_outputs=[audio_output],\n",
    "        title=\"Chat with Nova\",\n",
    "        description=\"Ask about tickets, automation services, pricing, or integration and Nova will also speak her reply.\"\n",
    "    )\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    demo.launch()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llm-engineering",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
